import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SpiralMatrix {

    public int[][] spiralMatrix(int m, int n, ListNode head) {
        List<Integer> list = new ArrayList<>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        int[][] ans = new int[m][n];
        for (int i = 0; i < m; i++) {
            Arrays.fill(ans[i], -1);
        }
        int a = 0;
        int b = 0;
        int c = m - 1;
        int d = n - 1;
        int temp = 0;
        while (a <= c && b <= d) {
            temp = process(list, a, b, c, d, temp, ans);
            a++;
            b++;
            c--;
            d--;
        }
        return ans;
    }

    public int process(List<Integer> list, int m, int n, int a, int b, int i, int[][] ans) {
        int index = n;
        while (index <= b && i < list.size()) {
            ans[m][index++] = list.get(i++);
        }
        index = m + 1;
        while (index <= a && i < list.size()) {
            ans[index++][b] = list.get(i++);
        }
        index = b - 1;
        while (index >= n && i < list.size()) {
            ans[a][index--] = list.get(i++);
        }
        index = a - 1;
        while (index > m && i < list.size()) {
            ans[index--][n] = list.get(i++);
        }
        return i;
    }
}
